package controllers.factories;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lib_model.Account.Account;
import lib_model.Account.Account_factory;
import lib_model.Account.Account_warehouse;
import lib_model.Transportion.Transportion_bill;
import lib_model.Transportion.Transportion_bill_details;

/**
 * Servlet implementation class Transporter
 */
@WebServlet("/factories/Transporter")
public class Transporter extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Transporter() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
		int productid = Integer.parseInt(request.getParameter("productid"));
		int warehouseid = Integer.parseInt(request.getParameter("warehouseid"));
		int quantity = Integer.parseInt(request.getParameter("txtQuan"));
		Transportion_bill bill = new Transportion_bill();
		Account acc = (Account) request.getSession().getAttribute("User");
		String usn = acc.username;
		int fac_id = 0;
		fac_id = ((Account_factory) (new Account_factory(usn).GetInformation().ObjResult)).factory_id_ref;
		bill.transportion_type_name_ref = "Processed";
		bill.warehouse_id_ref = warehouseid;
		bill.account_factory_username_ref = ((Account)request.getSession().getAttribute("User")).username;
		bill.factory_id_ref = fac_id;
		Account_warehouse ac = new Account_warehouse();
		ArrayList<Account_warehouse> ls = (ArrayList<Account_warehouse>)ac.Select().ObjResult;
		String AccountUser = "";
		for(Account_warehouse lss : ls){
			if(lss.warehouse_id_ref == warehouseid){
				AccountUser = ((Account_warehouse)(lss.GetInformation().ObjResult)).username_ref;
				break;
			}
		}
		bill.account_warehouse_username_get_ref = AccountUser;
		Transportion_bill_details detail = new Transportion_bill_details();
		detail.products_id_ref = productid;
		detail.transportion_billid_id_ref = Integer.parseInt((bill.Add().ObjResult.toString()));
		detail.quantity = quantity;
		detail.Add();
		response.sendRedirect("../factories/transportion-bill.jsp");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
